package com.cloud.api.user.controller;

import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cloud.api.base.BaseController;
import com.cloud.api.user.service.UserService;
import com.cloud.api.util.JwtTokenUtil;
import com.cloud.common.exception.CloudException;
import com.cloud.common.result.ExecuteResult;
import com.cloud.common.util.jwt.IJWTInfo;
import com.cloud.common.util.jwt.JWTInfo;

import reactor.core.publisher.Mono;

@RestController
@RequestMapping("/guest")
public class GuestController extends BaseController {

	@Autowired
	private UserService userService;

	@Autowired
	private JwtTokenUtil jwtTokenUtil;

	/**
	 * 游客登录，如果不存在返回给一个令牌
	 * 
	 * @param tokenParam
	 * @return
	 */
	@GetMapping("/login")
	public Mono<ExecuteResult<String>> login(@RequestHeader Map<String, String> requestHeader) {
		try {
			Object jwtToken = requestHeader.get("gametoken");
			if (StringUtils.isEmpty(jwtToken)||"null".equals(jwtToken)) {
				String newUserId = UUID.randomUUID().toString();
				return userService.register(newUserId).map(userClient -> {
					IJWTInfo jwtInfo = new JWTInfo("gust", userClient.getId(), "游客");
					String myJwtToken = "";
					try {
						myJwtToken = jwtTokenUtil.generateToken(jwtInfo);
					} catch (Exception e) {
						logger.error("解析失败！", e);
						throw new CloudException(-1, "解析失败！");
					}
					return myJwtToken;
				}).map(token -> {
					return ExecuteResult.ok("生成客户账号成功", (String) token);
				});
			}
//			ExecuteResult.ok((String)jwtToken);
			return Mono.just(ExecuteResult.ok("拿到token成功", (String) jwtToken));
		} catch (Exception e) {
			logger.error("游客登录失败", e);
			return Mono.just(ExecuteResult.fail("游客登录失败！"));
		}
	}

}